/*
 * MIT License
 *
 * Copyright (c) 2019 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.commons.file;

import cn.seaboot.commons.core.ClassPathResource;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * [扩展名 - MIME类型] 转换工具
 * <p>
 * 当前工具类，可以简化大部分的程序开发，但严格来说，逻辑上不是十分严谨：
 *
 * <li>实际上，一个 extension 可以对应多个 mime，一个 mime 也可以对应多个 extension；</li>
 * <li>js 文件的 mime 类型，既可以是 text/javascript，也可以是 application/javascript；</li>
 * <li>image/jpeg，同时是 jpg 和 jpeg 的 mime 类型;</li>
 * <li>而且，还存在非标准或自定义的 mime 类型。</li>
 *
 * @author Mr.css
 * @version 2020/6/3 添加几个常用的Mime类型常量
 */
public final class MimeUtils {
    private static final Logger logger = LoggerFactory.getLogger(MimeUtils.class);

    private MimeUtils() {
    }

    public static final String DOC = "doc";
    public static final String XLS = "xls";

    public static final String DOCX = "docx";
    public static final String XLSX = "xlsx";

    public static final String XML = "xml";
    public static final String JSON = "json";
    public static final String HTML = "html";

    public static final String PDF = "pdf";
    public static final String PNG = "png";
    public static final String JPG = "jpg";
    public static final String JPEG = "jpeg";

    /**
     * extension-mime 映射
     */
    private static final Map<String, String> EXTENSION_MIME_MAP = new HashMap<>();

    static {
        add(PDF, MediaType.APPLICATION_PDF_VALUE);

        add(XLS, MediaType.APPLICATION_XLS_VALUE);
        add(XLSX, MediaType.APPLICATION_XLSX_VALUE);

        add(DOC, MediaType.APPLICATION_DOC_VALUE);
        add(DOCX, MediaType.APPLICATION_DOCX_VALUE);

        add(HTML, MediaType.TEXT_HTML_VALUE);
        add(XML, MediaType.APPLICATION_XML_VALUE);
        add(JSON, MediaType.APPLICATION_JSON_VALUE);

        add(PNG, MediaType.IMAGE_PNG_VALUE);
        add(JPG, MediaType.IMAGE_JPEG_VALUE);
        add(JPEG, MediaType.IMAGE_JPEG_VALUE);

        // 尝试载入 resources 文件夹中的配置
        try (InputStream inputStream = ClassPathResource.getInputStream("mime.properties")) {
            loadProperties(inputStream);
        } catch (IOException ignore) {
            logger.info("Read mime.properties failed!");
        }
    }

    /**
     * 从IO流中获取properties配置数据
     *
     * @param is input
     * @throws IOException -
     */
    public static void loadProperties(InputStream is) throws IOException {
        Properties properties = new Properties();
        properties.load(is);
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            add(entry.getValue().toString(), entry.getKey().toString());
        }
    }

    /**
     * 添加一个扩展名配置
     *
     * @param extension 扩展名
     * @param mimeType  mime
     */
    private static void add(String extension, String mimeType) {
        EXTENSION_MIME_MAP.put(extension, mimeType);
    }

    /**
     * 是否包含扩展名
     * <p>
     * Returns true if the given extension has an entry in the map.
     *
     * @param extension 扩展名 (i.e. png)
     * @return True iff there is a mimeType entry in the map.
     */
    public static boolean content(@NotNull String extension) {
        return EXTENSION_MIME_MAP.containsKey(extension);
    }

    /**
     * 根据扩展名获取对应的 MIME 类型
     * <p>
     * 一个扩展名可对应于多种 MIME 类型，这里只是返回其中一个值。
     * <p>
     * 需要注意当前类的管理，只保存优选的 mime 类型。
     *
     * @param extension 扩展名 (i.e. png)
     * @return The MIME type for the given extension or null iff there is none.
     */
    public static String getMimeType(@NotNull String extension) {
        return EXTENSION_MIME_MAP.get(extension);
    }
}